<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="1285px2px">
      <!-- 基本信息 -->
      <Basicinformation ref="Basicinformation" :basicInformationForm="form" :title="titles"></Basicinformation>
      <!-- 处置原则和要求 -->
      <Disposalprinciplesandrequirements ref="Disposalprinciplesandrequirements" :basicInformationForm="form"
        :title="titles">
      </Disposalprinciplesandrequirements>
      <!-- 救援小组 -->
      <rescueteam ref="rescueteam" :basicInformationForm="form" :title="titles"></rescueteam>
      <!-- 响应启动 -->
      <Responseinitiation ref="Responseinitiation" :basicInformationForm="form" :title="titles"></Responseinitiation>
      <!-- 应急保障 -->
      <Emergencysupportoptions ref="Emergencysupportoptions" :basicInformationForm="form" :title="titles">
      </Emergencysupportoptions>
      <!-- 处置措施 -->
      <disposalmeasures ref="disposalmeasures" :basicInformationForm="form" :title="titles"></disposalmeasures>
      <el-row style="margin-top: 20px">
        <el-col :span="8">
          <el-form-item label="" prop="remark">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </el-form-item></el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  getLists,
  insertData,
  deletelist,
  ModifierList,
} from "../../api/Genericmethods/GeneralQuery.js";
// 基本信息
import Basicinformation from "./components/Basicinformation.vue";
// 救援小组
import rescueteam from "./components/rescueteam.vue";
// 响应启动
import Responseinitiation from "./components/Responseinitiation.vue";
// 处置措施
import disposalmeasures from "./components/disposalmeasures.vue";
// 处置原则和要求
import Disposalprinciplesandrequirements from "./components/Disposalprinciplesandrequirements.vue";
// 应急保障
import Emergencysupportoptions from "./components/Emergencysupport.vue";
export default {
  // eslint-disable-next-line vue/no-unused-components
  components: {
    Basicinformation,
    rescueteam,
    Responseinitiation,
    disposalmeasures,
    Disposalprinciplesandrequirements,
    Emergencysupportoptions,
  },
  props: {},
  data() {
    return {
      form: {
        PlanName: "", //预案名称
        PlanType: "专项应急预案", //预案类型
        ApplicableScope: "", //适用范围
        ResponseLevel: "II级", //响应等级
        GradeName: "公司级", //等级名称
      },
      rules: {},
      titles: ""
    };
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 校验
    checkPlanNameUnique(rule, value, callback) {
      for (const item of this.$route.query.data) {
        if (value === item.PlanName) {
          this.$message.error("预案名称已存在");
        } else {
          callback();
        }
      }
    },
    // 取消按钮
    cancel() {
      this.$router.go(-1);
      this.$refs["form"].resetFields();
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 应急保障
          // this.$refs.Emergencysupportoptions.gelist();
          const emergent = this.$refs.Emergencysupportoptions.getFormData();
          const EmergeDisposalfieldlist =
            '`PlanName`,`PlanType`,`Program`,`SupportContent1`,`SupportContent2`,`SupportContent3`,`SupportContent4`,`SupportContent5`,`SupportContent6`,`SupportContent7`,`SupportContent8`,`SupportContent9`,`SupportContent10`';
          const EmergeinsertSql = [];
          for (let index = 0; index < emergent.length; index++) {
            const element = emergent[index];
            const Disposalresult = [
              this.form.PlanName,
              this.form.PlanType,
              element.name,
            ];
            for (let l = 0; l < 10; l++) {
              const value = element.Responseinitiation[l]?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
              Disposalresult.push(value);
            }
            const Disposalsql = `'${Disposalresult.join("','")}'`;
            EmergeinsertSql.push(Disposalsql);
          }
          //  console.log(EmergeinsertSql,"应急保障");
          //  基本信息
          // this.$refs.Basicinformation.gelist();
          const Basicfieldlist = Object.keys(this.form)
            .map((field) => `\`${field}\``)
            .join(",");
          const Basicresult = `${Object.values(this.form)
            .map((value) => `'${value}'`)
            .join(",")}`;

          //  处置原则
          // this.$refs.Disposalprinciplesandrequirements.gelist();
          const Disposalfieldlist =
            '`PlanName`,`PlanType`,`TenetContent1`,`TenetContent2`,`TenetContent3`,`TenetContent4`,`TenetContent5`,`TenetContent6`,`TenetContent7`,`TenetContent8`,`TenetContent9`,`TenetContent10`';
          const Disposalresult = [this.form.PlanName, this.form.PlanType];
          const dispod =
            this.$refs.Disposalprinciplesandrequirements.getFormData()
              .Disposalsteps;
          for (let l = 0; l < 10; l++) {
            const value = dispod[l]?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
            Disposalresult.push(value);
          }
          // console.log(Disposalresult);
          const Dealsql = `'${Disposalresult.join("','")}'`;
          // 救援小组职责
          // this.$refs.rescueteam.gelist();
          const resculist = this.$refs.rescueteam.getFormData();
          //救援小组机构
          const RscGroufieldlist =
            '`PlanType`,`PlanName`,`GroupLeader`,`GroupDeputy`,`GroupMember`';
          const RscGrouresult = `'${this.form.PlanType}','${this.form.PlanName}','${resculist.groupleader.Membershipgroup}','${resculist.Deputygroupleader.MembershipDeputygroup}','${resculist.Groupmembers.Membershipcomposition}'`;
          //救援小组职责
          // 组长
          const Teamfieldlist = `\`PlanType\`,\`PlanName\`,\`Category\`,\`Group\`,\`Claim1\`,\`Claim2\`, \`Claim3\`,\`Claim4\`,\`Claim5\`,\`Claim6\`,\`Claim7\`,\`Claim8\`,\`Claim9\`,\`Claim10\`,\`Duty1\`,\`Duty2\`,\`Duty3\`,\`Duty4\`,\`Duty5\`,\`Duty6\`,\`Duty7\`,\`Duty8\`,\`Duty9\`,\`Duty10\``;
          const Teamresult = [
            this.form.PlanType,
            this.form.PlanName,
            "组长",
            "",
          ];
          for (let l = 0; l < 10; l++) {
            const value =
              resculist.groupleader
                .Responsibilitiesandrequirementsoftheteamleader[l]?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
            Teamresult.push(value);
          }
          for (let l = 0; l < 10; l++) {
            const value =
              resculist.groupleader.Emergencyresponsibilitiesoftheteamleader[l]
                ?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
            Teamresult.push(value);
          }
          const Disposalsql = `'${Teamresult.join("','")}'`;
          // // 副组长
          const Deputyfieldlist = `\`PlanType\`,\`PlanName\`,\`Category\`,\`Group\`,\`Claim1\`,\`Claim2\`, \`Claim3\`,\`Claim4\`,\`Claim5\`,\`Claim6\`,\`Claim7\`,\`Claim8\`,\`Claim9\`,\`Claim10\`,\`Duty1\`,\`Duty2\`,\`Duty3\`,\`Duty4\`,\`Duty5\`,\`Duty6\`,\`Duty7\`,\`Duty8\`,\`Duty9\`,\`Duty10\``;
          const Deputyresult = [
            this.form.PlanType,
            this.form.PlanName,
            "副组长",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
          ];
          for (let l = 0; l < 10; l++) {
            const value =
              resculist.Deputygroupleader
                .Emergencyresponsibilitiesofdeputyteamleader[l]?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
            Deputyresult.push(value);
          }
          const Deputysql = `'${Deputyresult.join("','")}'`;
          // 小组成员
          const Groupfieldlist = `\`PlanType\`,\`PlanName\`,\`Category\`,\`Group\`,\`Claim1\`,\`Claim2\`, \`Claim3\`,\`Claim4\`,\`Claim5\`,\`Claim6\`,\`Claim7\`,\`Claim8\`,\`Claim9\`,\`Claim10\`,\`Duty1\`,\`Duty2\`,\`Duty3\`,\`Duty4\`,\`Duty5\`,\`Duty6\`,\`Duty7\`,\`Duty8\`,\`Duty9\`,\`Duty10\``;
          const GroutSql = [];
          // 小组名称
          for (
            let index = 0;
            index < resculist.Groupmembers.Disposalstepslist.length;
            index++
          ) {
            const Groupmemelement =
              resculist.Groupmembers.Disposalstepslist[index];
            let sql = `'${this.form.PlanType}','${this.form.PlanName}','成员','${Groupmemelement.GroupName}','','','','','','','','','',''`;
            for (let l = 0; l < 10; l++) {
              const value =
                Groupmemelement.Emergencyresponsibilitiesofteammembers[l]
                  ?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
              sql += `,'${value}'`;
            }
            GroutSql.push(sql);
          }
          // 处置内容
          // this.$refs.disposalmeasures.gelist();
          const ActivityAreaList = this.$refs.disposalmeasures.getFormData();
          const sqllist =
            '`PlanType`,`PlanName`,`AccidentArea`,`AccidentPoint`,`MeasureName`,`DealCode`,`DealContent1`,`DealContent2`,`DealContent3`,`DealContent4`,`DealContent5`,`DealContent6`,`DealContent7`,`DealContent8`,`DealContent9`,`DealContent10`';
          const insertSql = [];
          for (let i = 0; i < ActivityAreaList.length; i++) {
            const area = ActivityAreaList[i];
            let AccidentArea = "";
            let AccidentPoint = "";

            if (area.zoneofaction === "设备") {
              AccidentPoint = area.AccidentArea;
            } else if (area.zoneofaction === "区域") {
              AccidentArea = area.AccidentArea;
            }
            for (let j = 0; j < area.Disposalserialnumber.length; j++) {
              const disposal = area.Disposalserialnumber[j];

              for (let k = 0; k < disposal.divContents.length; k++) {
                const content = disposal.divContents[k];

                const dealCode = j + 1;
                // let sql = `INSERT INTO IMP."EmergPlan_SiteRspMrs_Deal" ("PlanType","PlanName","AccidentArea","AccidentPoint","DealCode","MeasureName","DealContent1","DealContent2","DealContent3","DealContent4","DealContent5","DealContent6","DealContent7","DealContent8","DealContent9","DealContent10") VALUES (`;
                let sql = `'${this.form.PlanType}','${this.form.PlanName}','${AccidentArea}','${AccidentPoint}','${area.MeasureName}','${dealCode}'`;
                for (let l = 0; l < 10; l++) {
                  const value = content.contents[l]?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
                  sql += `,'${value}'`;
                }
                insertSql.push(sql);
              }
            }
          }
          // console.log(insertSql, "处置措施");
          //  响应启动
          // this.$refs.Responseinitiation.gelist();
          const DResponseinifieldlist =
            '`PlanName`,`PlanType`,`Program`,`WorkContent1`,`WorkContent2`,`WorkContent3`,`WorkContent4`,`WorkContent5`,`WorkContent6`,`WorkContent7`,`WorkContent8`,`WorkContent9`,`WorkContent10`';
          const ResponseinitSql = [];
          const Respon = this.$refs.Responseinitiation.getFormData();
          for (let index = 0; index < Respon.length; index++) {
            const element = Respon[index];
            const Disposalresult = [
              this.form.PlanName,
              this.form.PlanType,
              element.name,
            ];
            for (let l = 0; l < 10; l++) {
              const value = element.responseInitiation[l]?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
              Disposalresult.push(value);
            }
            const Disposalsql = `'${Disposalresult.join("','")}'`;
            ResponseinitSql.push(Disposalsql);
          }
          // console.log(ResponseinitSql,"响应启动");
          const sucsslist = [
            insertData("EmergPlan_SpecRspMrs", Basicfieldlist, Basicresult), //基本信息
            insertData(
              "EmergPlan_SpecRspMrs_DealTenet",
              Disposalfieldlist,
              Dealsql
            ), // 处置原则
            insertData(
              "EmergPlan_SpecRspMrs_RscGroupInst",
              RscGroufieldlist,
              RscGrouresult
            ), //小组机构
            insertData(
              "EmergPlan_SpecRspMrs_RscGroupDuty",
              Teamfieldlist,
              Disposalsql
            ), //组长
            insertData(
              "EmergPlan_SpecRspMrs_RscGroupDuty",
              Deputyfieldlist,
              Deputysql
            ), // 副组长
          ];
          // 救援小组成员
          for (let index = 0; index < GroutSql.length; index++) {
            const element = GroutSql[index];
            // 将每个请求添加到promises数组中
            const promise = insertData(
              "EmergPlan_SpecRspMrs_RscGroupDuty",
              Groupfieldlist,
              element
            );
            sucsslist.push(promise);
          }
          // 响应启动
          for (let index = 0; index < ResponseinitSql.length; index++) {
            const element = ResponseinitSql[index];
            // 将每个请求添加到promises数组中
            const promise = insertData(
              "EmergPlan_SpecRspMrs_RspInitiate",
              DResponseinifieldlist,
              element
            );
            sucsslist.push(promise);
          }
          // 处置措施
          for (let index = 0; index < insertSql.length; index++) {
            const element = insertSql[index];
            // 将每个请求添加到promises数组中
            const promise = insertData(
              "EmergPlan_SpecRspMrs_Deal",
              sqllist,
              element
            );
            sucsslist.push(promise);
          }
          // 应急保障
          for (let index = 0; index < EmergeinsertSql.length; index++) {
            const element = EmergeinsertSql[index];
            // 将每个请求添加到promises数组中
            const promise = insertData(
              "EmergPlan_SpecRspMrs_Support",
              EmergeDisposalfieldlist,
              element
            );
            sucsslist.push(promise);
          }
          // 使用Promise.all()等待所有请求完成
          // Promise.all(sucsslist)
          //   .then((res) => {
          //     console.log(res);
          //     for (let index = 0; index < res.length; index++) {
          //       const element = res[index];
          //       this.OperationLog(element, this.$route.meta.title);
          //       if (element.data.code === -1) {
          //         this.$message.error(element.data.message);
          //         return;
          //       } else {
          //         this.$modal.msgSuccess("新增成功");
          //         this.$router.replace("/Specialemergencyplan");
          //       }
          //     }
          //   })

          //   .catch((err) => {
          //     // 请求中有一个或多个失败
          //     this.$message.error(err);
          //   });

          Promise.all(sucsslist)
            .then((res) => {
              console.log(res);
              for (let index = 0; index < res.length; index++) {
                const element = res[index];
                this.OperationLog(element, this.$route.meta.title);
                if (element.data.code === -1) {
                  this.$message.error(element.data.message);
                  return;
                }
              }
              this.$router.replace("/Specialemergencyplan");
            })
            .then(() => {
              this.$modal.msgSuccess("新增成功");
            })
            .catch((error) => {
              console.log(error);
            });
        } else {
          return this.$message.error(false);
        }
      });
    },
    OperationLog(res, title) {
      // INSERT INTO IMP."OperationLogList" ("timestamp","SQL","TIP","code","message","title") VALUES ('1','2','3','4','6','7')
      const timestamp = "'" + res.data.timestamp + "'";
      const SQL = "'" + res.getAllParams.SQL.replace(/'/g, "\\'") + "'";
      const TIP = "'" + res.getAllParams.TIP + "'";
      const code = "'" + res.data.code + "'";
      const message = "'" + res.data.message + "'";
      const titles = "'" + title + "'";
      const parameter = "OperationLogList";
      const fieldlist = '`timestamp`,`SQL`,`TIP`,`code`,`message`,`title`';
      const result = `${timestamp}, ${SQL}, ${TIP}, ${code}, ${message}, ${titles}`;
      insertData(parameter, fieldlist, result);
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.titles = this.$route.query.title
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() { },
  beforeCreate() { }, // 生命周期 - 创建之前
  beforeMount() { }, // 生命周期 - 挂载之前
  beforeUpdate() { }, // 生命周期 - 更新之前
  updated() { }, // 生命周期 - 更新之后
  beforeDestroy() { }, // 生命周期 - 销毁之前
  destroyed() { }, // 生命周期 - 销毁完成
  activated() { }, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="scss" scoped></style>
